package com.app.aspect;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLock {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    private static final long DEFAULT_WAIT_TIME = 1000; // 默认等待时间
    private static final int DEFAULT_MAX_ATTEMPTS = 3; // 默认最大尝试次数

    /**
     * 加锁
     * @param key 键
     * @param value 值
     * @param timeout 超时时间
     * @return 是否获取到锁
     */
    public boolean lock(String key, String value, long timeout) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        Boolean success = ops.setIfAbsent(key, value, timeout, TimeUnit.MILLISECONDS);
        return success != null && success;
    }

    /**
     * 解锁
     * @param key 键
     */
    public void unlock(String key) {
        stringRedisTemplate.delete(key);
    }



}
